﻿using BlazorApp.Model;
using BootstrapBlazor.Components;
using EnumsNET;
using Microsoft.AspNetCore.Components;
using Model.Dtos;
using Model.Enum;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Utils;


namespace BlazorApp.Pages
{
    public partial class StudentPage
    {
        private static IEnumerable<int> PageItemsSource => new int[] { 5, 10, 20 };

        [Inject]
        private HttpHelper HttpHelper { get; set; }

        private List<Student>? Items { get; set; }

        private static readonly ConcurrentDictionary<Type, Func<IEnumerable<Student>, string, SortOrder, IEnumerable<Student>>> SortLambdaCache = new();

        //private Student SearchModel { get; set; } = new Student();
        private DateTime? Birth_Start { get; set; }
        private DateTime? Birth_End { get; set; }

        private List<SelectedItem> StateItems { get; set; } = new List<SelectedItem>();

        private List<SelectedItem> SexItems { get; set; } = new List<SelectedItem>();

        protected override void OnInitialized()
        {
            StateItems.Add(new SelectedItem("", "全部"));
            foreach (var item in Enums.GetMembers<StudentEnum.StateEnum>())
            {
                StateItems.Add(new SelectedItem(item.ToInt32().ToString(), item.Attributes.Get<DescriptionAttribute>().Description));
            }

            SexItems.Add(new SelectedItem("", "全部"));
            foreach (var item in Enums.GetMembers<StudentEnum.SexEnum>())
            {
                SexItems.Add(new SelectedItem(item.ToInt32().ToString(), item.Attributes.Get<DescriptionAttribute>().Description));
            }
        }

        private async Task<QueryData<Student>> OnQueryAsync(QueryPageOptions options)
        {
            Student student = options.SearchModel as Student;
            //var dicts = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(student));
            var dicts = student.GetType().GetProperties().ToDictionary(q => q.Name, q => q.GetValue(student));
            //将Birth查询条件加入条件中
            if (Birth_Start != null)
            {
                dicts.Add("Birth_Start", Birth_Start?.ToString("yyyy-MM-dd"));
            }
            else
            {
                dicts.Add("Birth_Start", null);//一定要加这个，否则Sqlsugar就不能用WhereIF
            }

            if (Birth_End != null)
            {
                dicts.Add("Birth_End", Birth_End?.ToString("yyyy-MM-dd"));
            }
            else
            {
                dicts.Add("Birth_End", null);//一定要加这个，否则Sqlsugar就不能用WhereIF
            }

            options.SearchModel = dicts;
            Debug.WriteLine(JsonConvert.SerializeObject(options));

            QueryResult<Student> queryResult = await HttpHelper.PostResponse<QueryResult<Student>>("/api/student/list", JsonConvert.SerializeObject(options));
            IEnumerable<Student> items = queryResult.ResultList;


            // 设置记录总数
            var total = queryResult.TotalCount;

            //// 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                items = items.Where(options.Filters.GetFilterFunc<Student>());
                isFiltered = true;
            }

            //// 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                var invoker = SortLambdaCache.GetOrAdd(typeof(Student), key => LambdaExtensions.GetSortLambda<Student>().Compile());
                items = invoker(items, options.SortName, options.SortOrder);
                isSorted = true;
            }

            return new QueryData<Student>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = false
            };
        }

        private static Task<Student> OnAddAsync() => Task.FromResult(new Student() { State = (int)StudentEnum.StateEnum.State1, Sex = null });

        private async Task<bool> OnSaveAsync(Student item, ItemChangedType changedType)
        {
            ReturnResult returnResult = await HttpHelper.PostResponse<ReturnResult>("/api/student/save", JsonConvert.SerializeObject(item));
            return returnResult.State;
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<Student> items)
        {
            var idItems = items.Select(i => i.Id).ToList();
            ReturnResult returnResult = await HttpHelper.PostResponse<ReturnResult>("/api/student/delete", JsonConvert.SerializeObject(idItems));
            return returnResult.State;
        }

        private Task OnResetSearchAsync(Student item)
        {
            Utility.Reset(item);
            Birth_Start = null;
            Birth_End = null;
            return Task.CompletedTask;
        }

        //private static Task<string> AddressFormatter(object? d)
        //{
        //    var ret = "";
        //    var data = d as TableColumnContext<Student, object?>;
        //    if (data != null && data.Value != null)
        //    {
        //        var val = (string)data.Value;
        //        ret = val[..5] + "...";
        //    }
        //    return Task.FromResult(ret);
        //}

        //public static IEnumerable<SelectedItem> GetSelectItem(Enum en)
        //{
        //    List<SelectedItem> items = new List<SelectedItem>();
        //    items.Add(new SelectedItem("", ""));
        //    foreach (var item in Enums.GetMembers<en.GetType()>())
        //    {
        //        items.Add(new SelectedItem(item.ToInt32() == 0?"false":"true", item.Attributes.Get<DescriptionAttribute>().Description));
        //    }
        //    return items;
        //}
    }
}